<template>
  <div class="wholesale-price-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>批发价格管理</h2>
      <p>管理批发价格体系，包括阶梯价格、批量折扣、季节性价格等</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="价格类型">
          <el-select v-model="searchForm.priceType" placeholder="请选择价格类型" clearable style="width: 150px">
            <el-option label="阶梯价格" value="tiered" />
            <el-option label="批量折扣" value="bulk" />
            <el-option label="季节性价格" value="seasonal" />
            <el-option label="促销价格" value="promotion" />
            <el-option label="VIP价格" value="vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select v-model="searchForm.customerLevel" placeholder="请选择客户等级" clearable style="width: 150px">
            <el-option label="VIP" value="VIP" />
            <el-option label="一级" value="一级" />
            <el-option label="二级" value="二级" />
            <el-option label="三级" value="三级" />
            <el-option label="普通" value="普通" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="生效" value="active" />
            <el-option label="待生效" value="pending" />
            <el-option label="已失效" value="expired" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd" :icon="Plus">新增价格</el-button>
        <el-button type="success" @click="handleBatchApprove" :icon="Check" :disabled="!selectedRows.length">
          批量审核
        </el-button>
        <el-button type="warning" @click="handleBatchUpdate" :icon="Edit" :disabled="!selectedRows.length">
          批量调价
        </el-button>
        <el-button type="info" @click="handleExport" :icon="Download">导出价格</el-button>
        <el-button type="info" @click="handleImport" :icon="Upload">导入价格</el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="filteredTableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column prop="productName" label="商品名称" width="200" show-overflow-tooltip />
        <el-table-column prop="priceType" label="价格类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getPriceTypeTagType(row.priceType)">{{ getPriceTypeText(row.priceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerLevel" label="客户等级" width="100" />
        <el-table-column prop="basePrice" label="基础价格" width="120">
          <template #default="{ row }">
            ¥{{ row.basePrice.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="discountRate" label="折扣率" width="100">
          <template #default="{ row }">
            {{ row.discountRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="finalPrice" label="最终价格" width="120">
          <template #default="{ row }">
            ¥{{ row.finalPrice.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="minQuantity" label="最小数量" width="100" />
        <el-table-column prop="effectiveDate" label="生效日期" width="120" />
        <el-table-column prop="expiryDate" label="失效日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)" :icon="View">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
            <el-dropdown @command="(command) => handleCommand(command, row)">
              <el-button type="info" size="small" :icon="MoreFilled">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="copy" :icon="CopyDocument">复制价格</el-dropdown-item>
                  <el-dropdown-item command="history" :icon="Clock">价格历史</el-dropdown-item>
                  <el-dropdown-item command="approve" :icon="Check" v-if="row.status === 'pending'">审核通过</el-dropdown-item>
                  <el-dropdown-item command="reject" :icon="Close" v-if="row.status === 'pending'">审核拒绝</el-dropdown-item>
                  <el-dropdown-item command="disable" :icon="Lock" v-if="row.status === 'active'">停用</el-dropdown-item>
                  <el-dropdown-item command="enable" :icon="Unlock" v-if="row.status === 'expired'">启用</el-dropdown-item>
                  <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 价格详情对话框 -->
    <el-dialog
      v-model="priceDetailVisible"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
    >
      <PriceForm
        v-if="priceDetailVisible"
        :price-data="currentPrice"
        :mode="dialogMode"
        @save="handleSavePrice"
        @cancel="priceDetailVisible = false"
      />
    </el-dialog>

    <!-- 价格历史对话框 -->
    <el-dialog
      v-model="priceHistoryVisible"
      title="价格历史记录"
      width="70%"
    >
      <el-table :data="priceHistory" stripe>
        <el-table-column prop="changeDate" label="变更日期" width="150" />
        <el-table-column prop="oldPrice" label="原价格" width="120">
          <template #default="{ row }">
            ¥{{ row.oldPrice.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="newPrice" label="新价格" width="120">
          <template #default="{ row }">
            ¥{{ row.newPrice.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="changeReason" label="变更原因" show-overflow-tooltip />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="approver" label="审核人" width="120" />
      </el-table>
    </el-dialog>

    <!-- 批量调价对话框 -->
    <el-dialog
      v-model="batchUpdateVisible"
      title="批量调价"
      width="50%"
    >
      <el-form :model="batchUpdateForm" label-width="120px">
        <el-form-item label="调价方式">
          <el-radio-group v-model="batchUpdateForm.updateType">
            <el-radio label="percentage">按百分比</el-radio>
            <el-radio label="amount">按金额</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调价幅度">
          <el-input-number
            v-model="batchUpdateForm.updateValue"
            :precision="2"
            style="width: 200px"
          />
          <span style="margin-left: 10px">
            {{ batchUpdateForm.updateType === 'percentage' ? '%' : '元' }}
          </span>
        </el-form-item>
        <el-form-item label="调价原因">
          <el-input
            v-model="batchUpdateForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调价原因"
          />
        </el-form-item>
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="batchUpdateForm.effectiveDate"
            type="date"
            placeholder="选择生效日期"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchUpdateVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmBatchUpdate">确认调价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Refresh, Plus, Check, Edit, Download, Upload, View, MoreFilled,
  CopyDocument, Clock, Close, Lock, Unlock, Delete
} from '@element-plus/icons-vue'
import PriceForm from './components/PriceForm.vue'

// 响应式数据
const loading = ref(false)
const selectedRows = ref([])
const priceDetailVisible = ref(false)
const priceHistoryVisible = ref(false)
const batchUpdateVisible = ref(false)
const dialogMode = ref('add')
const currentPrice = ref(null)

// 搜索表单
const searchForm = reactive({
  productName: '',
  priceType: '',
  customerLevel: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 批量调价表单
const batchUpdateForm = reactive({
  updateType: 'percentage',
  updateValue: 0,
  reason: '',
  effectiveDate: ''
})

// 价格历史数据
const priceHistory = ref([])

// 模拟表格数据
const tableData = ref([
  {
    id: 1,
    productCode: 'P001',
    productName: '苹果iPhone 15',
    priceType: 'tiered',
    customerLevel: 'VIP',
    basePrice: 6999,
    discountRate: 15,
    finalPrice: 5949,
    minQuantity: 10,
    effectiveDate: '2024-01-01',
    expiryDate: '2024-12-31',
    status: 'active'
  },
  {
    id: 2,
    productCode: 'P002',
    productName: '华为Mate 60',
    priceType: 'bulk',
    customerLevel: '一级',
    basePrice: 5999,
    discountRate: 12,
    finalPrice: 5279,
    minQuantity: 20,
    effectiveDate: '2024-01-15',
    expiryDate: '2024-06-30',
    status: 'active'
  },
  {
    id: 3,
    productCode: 'P003',
    productName: '小米14 Pro',
    priceType: 'seasonal',
    customerLevel: '二级',
    basePrice: 4999,
    discountRate: 10,
    finalPrice: 4499,
    minQuantity: 15,
    effectiveDate: '2024-02-01',
    expiryDate: '2024-04-30',
    status: 'pending'
  },
  {
    id: 4,
    productCode: 'P004',
    productName: 'OPPO Find X7',
    priceType: 'promotion',
    customerLevel: '三级',
    basePrice: 4599,
    discountRate: 8,
    finalPrice: 4231,
    minQuantity: 25,
    effectiveDate: '2024-03-01',
    expiryDate: '2024-03-31',
    status: 'expired'
  },
  {
    id: 5,
    productCode: 'P005',
    productName: 'vivo X100',
    priceType: 'vip',
    customerLevel: 'VIP',
    basePrice: 3999,
    discountRate: 20,
    finalPrice: 3199,
    minQuantity: 5,
    effectiveDate: '2024-01-01',
    expiryDate: '2024-12-31',
    status: 'active'
  }
])

// 计算属性
const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (searchForm.productName) {
    data = data.filter(item => 
      item.productName.toLowerCase().includes(searchForm.productName.toLowerCase()) ||
      item.productCode.toLowerCase().includes(searchForm.productName.toLowerCase())
    )
  }
  
  if (searchForm.priceType) {
    data = data.filter(item => item.priceType === searchForm.priceType)
  }
  
  if (searchForm.customerLevel) {
    data = data.filter(item => item.customerLevel === searchForm.customerLevel)
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  pagination.total = data.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return data.slice(start, end)
})

const dialogTitle = computed(() => {
  const titles = {
    add: '新增价格',
    edit: '编辑价格',
    view: '查看价格详情'
  }
  return titles[dialogMode.value] || '价格管理'
})

// 方法
const getPriceTypeText = (type) => {
  const types = {
    tiered: '阶梯价格',
    bulk: '批量折扣',
    seasonal: '季节性价格',
    promotion: '促销价格',
    vip: 'VIP价格'
  }
  return types[type] || type
}

const getPriceTypeTagType = (type) => {
  const tagTypes = {
    tiered: 'primary',
    bulk: 'success',
    seasonal: 'warning',
    promotion: 'danger',
    vip: 'info'
  }
  return tagTypes[type] || 'info'
}

const getStatusText = (status) => {
  const statuses = {
    active: '生效',
    pending: '待生效',
    expired: '已失效'
  }
  return statuses[status] || status
}

const getStatusTagType = (status) => {
  const tagTypes = {
    active: 'success',
    pending: 'warning',
    expired: 'info'
  }
  return tagTypes[status] || 'info'
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    productName: '',
    priceType: '',
    customerLevel: '',
    status: ''
  })
  pagination.currentPage = 1
  loadData()
}

const handleAdd = () => {
  dialogMode.value = 'add'
  currentPrice.value = null
  priceDetailVisible.value = true
}

const handleView = (row) => {
  dialogMode.value = 'view'
  currentPrice.value = { ...row }
  priceDetailVisible.value = true
}

const handleEdit = (row) => {
  dialogMode.value = 'edit'
  currentPrice.value = { ...row }
  priceDetailVisible.value = true
}

const handleCommand = async (command, row) => {
  switch (command) {
    case 'copy':
      handleCopy(row)
      break
    case 'history':
      handleViewHistory(row)
      break
    case 'approve':
      await handleApprove(row)
      break
    case 'reject':
      await handleReject(row)
      break
    case 'disable':
      await handleDisable(row)
      break
    case 'enable':
      await handleEnable(row)
      break
    case 'delete':
      await handleDelete(row)
      break
  }
}

const handleCopy = (row) => {
  dialogMode.value = 'add'
  currentPrice.value = { ...row, id: null }
  priceDetailVisible.value = true
}

const handleViewHistory = (row) => {
  // 模拟价格历史数据
  priceHistory.value = [
    {
      changeDate: '2024-01-01',
      oldPrice: 7999,
      newPrice: 6999,
      changeReason: '年度调价',
      operator: '张三',
      approver: '李四'
    },
    {
      changeDate: '2023-12-01',
      oldPrice: 8999,
      newPrice: 7999,
      changeReason: '促销活动',
      operator: '王五',
      approver: '赵六'
    }
  ]
  priceHistoryVisible.value = true
}

const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确认审核通过该价格吗？', '确认操作', {
      type: 'warning'
    })
    
    // 模拟API调用
    row.status = 'active'
    ElMessage.success('审核通过成功')
  } catch {
    // 用户取消操作
  }
}

const handleReject = async (row) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入拒绝原因', '审核拒绝', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '请输入拒绝原因'
    })
    
    // 模拟API调用
    row.status = 'expired'
    ElMessage.success('审核拒绝成功')
  } catch {
    // 用户取消操作
  }
}

const handleDisable = async (row) => {
  try {
    await ElMessageBox.confirm('确认停用该价格吗？', '确认操作', {
      type: 'warning'
    })
    
    row.status = 'expired'
    ElMessage.success('停用成功')
  } catch {
    // 用户取消操作
  }
}

const handleEnable = async (row) => {
  try {
    await ElMessageBox.confirm('确认启用该价格吗？', '确认操作', {
      type: 'warning'
    })
    
    row.status = 'active'
    ElMessage.success('启用成功')
  } catch {
    // 用户取消操作
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该价格吗？删除后不可恢复！', '确认删除', {
      type: 'error'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消操作
  }
}

const handleBatchApprove = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要审核的价格')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认批量审核通过 ${selectedRows.value.length} 个价格吗？`, '批量审核', {
      type: 'warning'
    })
    
    selectedRows.value.forEach(row => {
      if (row.status === 'pending') {
        row.status = 'active'
      }
    })
    
    ElMessage.success('批量审核成功')
    selectedRows.value = []
  } catch {
    // 用户取消操作
  }
}

const handleBatchUpdate = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要调价的商品')
    return
  }
  
  batchUpdateForm.updateType = 'percentage'
  batchUpdateForm.updateValue = 0
  batchUpdateForm.reason = ''
  batchUpdateForm.effectiveDate = ''
  batchUpdateVisible.value = true
}

const handleConfirmBatchUpdate = () => {
  if (!batchUpdateForm.updateValue) {
    ElMessage.warning('请输入调价幅度')
    return
  }
  
  if (!batchUpdateForm.reason) {
    ElMessage.warning('请输入调价原因')
    return
  }
  
  // 模拟批量调价
  selectedRows.value.forEach(row => {
    if (batchUpdateForm.updateType === 'percentage') {
      row.finalPrice = row.basePrice * (1 - row.discountRate / 100) * (1 + batchUpdateForm.updateValue / 100)
    } else {
      row.finalPrice = row.finalPrice + batchUpdateForm.updateValue
    }
    row.finalPrice = Math.round(row.finalPrice * 100) / 100
  })
  
  ElMessage.success('批量调价成功')
  batchUpdateVisible.value = false
  selectedRows.value = []
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleImport = () => {
  ElMessage.success('导入功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleSavePrice = (priceData) => {
  if (dialogMode.value === 'add') {
    const newId = Math.max(...tableData.value.map(item => item.id)) + 1
    tableData.value.unshift({ ...priceData, id: newId })
    ElMessage.success('新增价格成功')
  } else if (dialogMode.value === 'edit') {
    const index = tableData.value.findIndex(item => item.id === priceData.id)
    if (index > -1) {
      tableData.value[index] = { ...priceData }
      ElMessage.success('更新价格成功')
    }
  }
  
  priceDetailVisible.value = false
  loadData()
}

const loadData = () => {
  loading.value = true
  // 模拟API调用延迟
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.wholesale-price-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.action-buttons {
  text-align: right;
}

.action-buttons .el-button {
  margin-left: 10px;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wholesale-price-management {
    padding: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .action-buttons {
    text-align: left;
    margin-top: 15px;
  }
  
  .action-buttons .el-button {
    margin: 5px 5px 5px 0;
  }
  
  .pagination-container {
    text-align: center;
  }
}
</style>